/*
 * Copyright (c) 2016. Naivor.All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.myapplication.base.mvp;


import com.example.myapplication.base.ApiException;
import com.example.myapplication.utils.LogUtils;
import com.google.gson.JsonSyntaxException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * BasePresenter 是应用中所有Presenter的顶级抽象类，规定了Presenter的参数类型
 * <p>
 * Presenter：MVP架构中的P。
 * <p>
 */
public abstract class BasePresenter<T extends IBaseUiView> implements IBasePresenter {
    protected static final String TAG = "BasePresenter";

    protected int page = 0;

    protected T mUiView;

    protected CompositeDisposable disposables;

    protected boolean isNeedShowErrorView = false;

    protected boolean isNeedShowError = true;

//    protected boolean isHasMoreData = true;

    public BasePresenter() {
        disposables = new CompositeDisposable();
    }

    /**
     * Presenter 的 oncreate（）生命周期，在Activity中的 oncreate（）中调用
     * 作用：恢复状态，初始化数据
     *

     */
    @Override
    public void oncreate() {
    }

    @Override
    public void bindView(IBaseUiView view) {
        this.mUiView = (T) view;
    }

    /**
     * 获取View
     *
     * @return
     */
    @SuppressWarnings("unchecked")
//    @NonNull
    public T getView() {
        return mUiView;
    }


    /**
     * Presenter 的 onSave（）生命周期，在Activity中的 onSaveInstance（）中调用
     * 作用： 保存数据
     *
     */
    @Override
    public void onSave() {

    }


    /**
     * Presenter 的 onPause（）生命周期，在Activity中的 onPause（）中调用
     * 作用：解绑View，销毁View
     */
    @Override
    public void onStop() {
        cancle();
    }

    /**
     * Presenter 的 onDestroy（）生命周期，在Activity中的 onDestroy（）中调用
     * 作用：销毁持有的对象
     */
    @Override
    public void onDestroy() {
        if (disposables != null) {
            disposables.dispose();
            disposables.clear();
            disposables = null;
        }
        mUiView = null;
    }


    /**
     * 将网络请求添加到任务列表中
     *
     * @param sub
     */
    @Override
    public void addNetTask(Disposable sub) {
        if (disposables != null) {
            disposables.add(sub);
        }
    }

    /**
     * 从任务列表移除请求任务
     *
     * @param sub
     */
    @Override
    public void removeNetTask(Disposable sub) {
        if (disposables != null) {
            disposables.remove(sub);
        }
    }

    /**
     * 取消加载的方法
     */
    @Override
    public void cancle() {
        if (disposables != null && !disposables.isDisposed()) {
            disposables.clear();
        }
    }


    /**
     * 加载发生错误
     */
    @Override
    public void loadError(Throwable e) {
        e.printStackTrace();
        String errorMsg = "";
        int code = 0;
        if (e instanceof ApiException) {
            ApiException exception = (ApiException) e;
            errorMsg = exception.getMsg();
            code = exception.getStatus();
        } else if (e instanceof SocketTimeoutException) {
            errorMsg = "网络不太顺畅哦~";
            if (mUiView != null && isNeedShowErrorView) {
                mUiView.showErrorView();
            }
        } else if (e instanceof ConnectException) {
            errorMsg = "网络不太顺畅哦~";
            if (mUiView != null && isNeedShowErrorView) {
                mUiView.showErrorView();
            }
        } else if (e instanceof UnknownHostException) {
            errorMsg = "网络不太顺畅哦~";
            if (mUiView != null && isNeedShowErrorView) {
                mUiView.showErrorView();
            }
        } else if (e instanceof HttpException) {
            errorMsg = "网络不太顺畅哦~";
            if (mUiView != null && isNeedShowErrorView) {
                mUiView.showErrorView();
            }
        } else if (e instanceof NumberFormatException) {
            errorMsg = "服务器错误，请联系管理员";
        } else if (e instanceof JsonSyntaxException) {
            errorMsg = "服务器错误，请联系管理员";
        } else {
            errorMsg = "网络错误，请检查您的网络";
        }

        if (mUiView != null && isNeedShowError) {
            mUiView.showErrorMsg(code, errorMsg);
        }
        dismissLoading();
        LogUtils.info("htd",e.toString());
        System.out.print(e.toString());
    }

    @Override
    public void loadComplete() {
        dismissLoading();
    }


    /**
     * 取消加载对话框
     */
    @Override
    public void dismissLoading() {
        if (mUiView != null) {
            mUiView.dismissLoadingDialog();
        }
    }

    /**
     * 加载更多
     */
    @Override
    public int loadMore() {
        page++;
        return page;
    }

    /**
     * 刷新页面数据
     */
    @Override
    public void refreshPageData() {
        page = 0;
    }

    public boolean isLoadMore() {
        return page > 1;
    }

    /**
     * 显示加载对话框
     *
     * @param isShow
     */
    @Override
    public void showLoading(boolean isShow) {
        if (isShow && mUiView != null) {
            mUiView.showLoadingDialog();
        }
    }

    public void showLoadingNow(boolean isShow) {
        if (isShow && mUiView != null) {
            mUiView.showLoadingDialogNow(true);
        }
    }

    public void loadListData(boolean isRefresh) {
        showLoading(!isRefresh);
        if (isRefresh) {
            refreshPageData();
            isNeedShowErrorView = true;
        } else {
            isNeedShowErrorView = false;
        }
    }


}
